using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Xml;
using System.IO;
using CapstoneProject.Models;
using System.Net;

namespace CapstoneProject.Activities
{
    [Activity(Label = "Add Account")]
    public class EnterAccCredActivity : Activity
    {
        string fid;
        string fiUrl;
        string fiOrg;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.EnterAccCred);

            TextView header = FindViewById<TextView>(Resource.Id.CredentialsHeader);
            TextView bank = FindViewById<TextView>(Resource.Id.Bank);

            header.Text = "Adding account to " + Intent.GetStringExtra("User");
            bank.Text = "Financial Institution: " + Intent.GetStringExtra("Bank");

            Button proceedButton = FindViewById<Button>(Resource.Id.AddAccountButton);
            proceedButton.Click += Proceed;
        }

        private void Proceed(object sender, EventArgs e)
        {
            TextView error = FindViewById<TextView>(Resource.Id.CredentialsError);
            EditText username = FindViewById<EditText>(Resource.Id.UsernameField);
            EditText password = FindViewById<EditText>(Resource.Id.PasswordField);
            EditText account = FindViewById<EditText>(Resource.Id.AccountField);
            EditText routing = FindViewById<EditText>(Resource.Id.RoutingField);
            if (String.IsNullOrEmpty(username.Text) || String.IsNullOrEmpty(password.Text) || String.IsNullOrEmpty(account.Text) || String.IsNullOrEmpty(routing.Text))
            {
                error.Text = "All fields are required.";
            }
            else
            {
                Account existingAccount = ((CapstoneApplication)Application).AccountRepository.GetAllAccounts().FirstOrDefault(a => a.BankAccountId == account.Text);
                if (existingAccount == null)
                {
                    GetFIInfo(Intent.GetStringExtra("Bank"));
                    BankStatement statement = new BankStatement() 
                    { 
                        UserId = username.Text,
                        Password = password.Text,
                        FiUrl = fiUrl,
                        FiOrg = fiOrg,
                        Fid = fid,
                        AccountId = account.Text,
                        BankId = routing.Text
                    };
                    string test = statement.GetBalance();
                    if (test != "Invalid.")
                    {
                        User user = ((CapstoneApplication)Application).UserRepository.GetAllUsers().FirstOrDefault(u => u.Username == Intent.GetStringExtra("User"));
                        Intent i = new Intent();
                        i.SetClass(this, typeof(NameAccountActivity));
                        i.AddFlags(ActivityFlags.NewTask);
                        i.PutExtra("Username", username.Text);
                        i.PutExtra("Password", password.Text);
                        i.PutExtra("FiUrl", fiUrl);
                        i.PutExtra("FiOrg", fiOrg);
                        i.PutExtra("Fid", fid);
                        i.PutExtra("AccountNumber", account.Text);
                        i.PutExtra("Routing", routing.Text);
                        i.PutExtra("UserId", user.UserId);
                        StartActivity(i);
                    }
                    else
                    {
                        error.Text = "Double check your credentials and try again.";
                    }
                }
            }
        }

        private void GetFIInfo(string fiorg)
        {
            OFXHome ofxh = new OFXHome();
            var searchedBanks = ofxh.Search(fiorg);
            string ofxId = "";
            foreach (string s in searchedBanks)
            {
                using (XmlReader xmlreader = XmlReader.Create(new StringReader(s)))
                {
                    xmlreader.ReadToFollowing("institutionid");
                    xmlreader.MoveToFirstAttribute();
                    if (xmlreader.Value == fiorg)
                    {
                        xmlreader.MoveToNextAttribute();
                        ofxId = xmlreader.Value;
                    }
                }
            }
            WebRequest request = WebRequest.Create("http://www.ofxhome.com/api.php?lookup=" + ofxId);
            request.Credentials = CredentialCache.DefaultCredentials;
            var stream = request.GetResponse().GetResponseStream();

            var reader = new StreamReader(stream);
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                if (line.Contains("<fid>"))
                {
                    fid = AssignValues("fid", line);
                }
                else if (line.Contains("<org>"))
                {
                    fiOrg = AssignValues("org", line);
                }
                else if (line.Contains("<url>"))
                {
                    fiUrl = AssignValues("url", line);
                }
            }
        }

        private string AssignValues(string element, string line)
        {
            using (XmlReader xmlreader = XmlReader.Create(new StringReader(line)))
            {
                xmlreader.ReadToFollowing(element);
                return xmlreader.ReadElementContentAsString();
            }
        }
    }
}